<?php

namespace tmcore\services\notice\mail;

use app\common\enum\MsgEnum;
use app\common\jobs\notice\MailJob;
use app\common\model\notice\UserNoticeLog;
use tmcore\services\MailService;
use tmcore\services\notice\BaseNotice;

class MailSendService extends BaseNotice
{
    /**
     * 发送消息
     * @param array $config
     * @param array $params ['uid' => '用户id', 'email' => '邮箱', 'expire_time' => '验证码过期时间', 'template' => '邮件模板参数']
     * @param bool $is_async
     * @return bool|mixed
     */
    public function send($config, $params, $is_async = false) {

        if(empty($params['email']) || empty($params['template'])) return self::setError('参数校验失败');
        if($config['is_captcha'] && empty($params['template']['code'])) return self::setError('参数校验失败');

        $content = $this->getContent($params['template'], $config['mail_template']['content']??'');

        $notice_log = UserNoticeLog::create([
            'scene'       => $config['scene'],
            'msg_token'   => $config['msg_token'],
            'uid'         => $params['uid']??0,
            'account'     => $params['email'],
            'title'       => $config['name'],
            'code'        => $config['is_captcha']?$params['template']['code']:'',
            'content'     => $content,
            'error'       => '',
            'notice_type' => $config['type'],
            'send_type'   => MsgEnum::MAIL_TYPE,
            'status'      => 0,
            'is_read'     => 0,
            'is_captcha'  => $config['is_captcha'],
            'expire_time' => $params['expire_time']??time()+900,
        ]);

        if(empty($notice_log['id'])) return self::setError('添加日志失败');

        if(empty($params['template']['info_subject'])) $params['template']['info_subject'] = $config['name'];
        if(empty($params['template']['info_body'])) $params['template']['info_body'] = $content;

        if($is_async) {
            //加入异步队列
            MailJob::pushJob([
                'job' => 'mailJob',
                'data' => [
                    'email' => $params['email'],
                    'templateParams' => $params['template'],
                    'id' => $notice_log['id']
                ]
            ]);
            return true;
        } else {
            return $this->sendMail($params['email'], $params['template'], $notice_log['id']);
        }
    }

    /**
     * 发送邮件
     * @param $email
     * @param $templateParams
     * @param $log_id
     * @return bool
     */
    public function sendMail($email, $templateParams, $log_id) {
        try {
            $mail = new MailService();
            //设置发件人
            if(!empty($templateParams['from_address'])) {
                $mail->setFrom($templateParams['from_address'],$templateParams['from_name']??'');
            }
            //设置收件人
            $mail->setReceiver($email,$templateParams['receiver_name']??'');
            //设置抄送
            if(!empty($templateParams['cc_address'])) {
                $mail->setCc($templateParams['cc_address'],$templateParams['cc_name']??'');
            }
            //设置秘密抄送
            if(!empty($templateParams['bcc_address'])) {
                $mail->setBcc($templateParams['bcc_address'],$templateParams['bcc_name']??'');
            }
            //设置HTML格式
            $mail->isHTML(false);
            //设置附件
            if(!empty($templateParams['attachment_path'])) {
                $mail->setAttachment($templateParams['attachment_path'],$templateParams['attachment_name']??'');
            }
            //设置邮件主题、内容
            if(!empty($templateParams['info_subject'])) {
                $mail->setMailInfo($templateParams['info_subject'],$templateParams['info_body']??'');
            }
            $mail->sendMail(); //发送
            $this->sendSuccess($log_id);
            return true;
        } catch (\Exception $e) {
            $this->sendFail($log_id, $e->getMessage());
            return self::setError($e->getMessage());
        }
    }
}